/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */

import { PathUtil } from '@ohos/hvigor';
import * as fs from 'fs';
import * as path from 'path';

import { Report } from '../../../../src/base/common/report/report.js';
import { ReportListener } from '../../../../src/base/common/report/report-listener.js';
import { ReportServiceImpl } from '../../../../src/base/common/report/report-service-impl.js';

describe('report', () => {
  test.concurrent('report', () => {
    const service = ReportServiceImpl.getInstance();
    service.addListener(TestLog.getInstance());
    service.report();
    const filePath = path.resolve(PathUtil.getHvigorCacheDir(), 'report', 'report.json');
    expect(fs.existsSync(filePath)).toEqual(true);
    const reportObj = JSON.parse(fs.readFileSync(filePath).toString());
    fs.rmdirSync(path.resolve(PathUtil.getHvigorCacheDir()), { recursive: true });
    expect(reportObj['version']).toEqual('1.0');
    expect(reportObj['testLog']).toEqual(['> hvigor Finished :feature:PreBuild... after 152 ms\n',
      '> hvigor Finished :feature:LegacyMergeProfile... after 3 ms 100 μs\n',
      '> hvigor Finished :feature:LegacyMakePackInfo... after 2 ms 150 μs\n',
      '> hvigor Finished :feature:BuildNativeWithCmake... after 96 μs\n',
      '> hvigor Finished :feature:BuildNativeWithNinja... after 38 μs\n',
      '> hvigor Finished :feature:ProcessLibs... after 3 ms 590 μs\n']);
    expect(reportObj['metrics']).toEqual(undefined);
  });
});

class TestLog implements ReportListener {
  private static instance: TestLog;

  private constructor() {
    //
  }

  queryReport(): Report<string[]> {
    return new Report('testLog',
      ['> hvigor Finished :feature:PreBuild... after 152 ms\n',
        '> hvigor Finished :feature:LegacyMergeProfile... after 3 ms 100 μs\n',
        '> hvigor Finished :feature:LegacyMakePackInfo... after 2 ms 150 μs\n',
        '> hvigor Finished :feature:BuildNativeWithCmake... after 96 μs\n',
        '> hvigor Finished :feature:BuildNativeWithNinja... after 38 μs\n',
        '> hvigor Finished :feature:ProcessLibs... after 3 ms 590 μs\n']
    );
  }

  static getInstance() {
    if (!TestLog.instance) {
      TestLog.instance = new TestLog();
    }
    return TestLog.instance;
  }
}
